package com.factory.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * http请求工具类
 */
@Slf4j
public class HttpUtil {

    /**
     * http请求连接超时间 3s
     */
    private static final int connectionTimeout = 3000;

    /**
     * socket请求处理超时间 10s
     */
    private static final int socketTimeout = 10000;

    /**
     * ping某个IP
     *
     * @param ip
     * @return
     */
    public static boolean ping(String ip, Integer timeOut) {
        if (StringUtil.isEmpty(ip)) return false;
        try {
            return InetAddress.getByName(ip).isReachable(timeOut);
        } catch (UnknownHostException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
    /**
     * 发送post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String post(String url, String param ,int num){
        log.info("发送post请求地址,{}",url);

        String response = "";// 要返回的response信息
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(socketTimeout);

        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");

        if (!StringUtils.isEmpty(param)) {
            //postMethod.setRequestBody(param);
            try {
                postMethod.setRequestEntity(new StringRequestEntity(param,"application/json","utf-8"));
            } catch (UnsupportedEncodingException e) {
                log.error("发送post请求时发生异常,{}",e);
                return response;
            }
        }
        //重试3次
        for (int i = 0; i < num; i++) {
            try {
                if (HttpStatus.SC_OK == httpClient.executeMethod(postMethod))
                    break;
            } catch (IOException e) {
                log.error("发送post请求异常,{}", e);
            }
        }

        try {
            response = postMethod.getResponseBodyAsString();
            log.info("发送post请求返回结果,{}", response);
        } catch (IOException e) {
            log.error("获取http请求的返回信息异常,{}", e);
        }

        postMethod.releaseConnection();

        return response;
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String post(String url, String param) {
        return post(url,param ,3);
    }

    /**
     * 发送post请求,新封装的方法
     *
     * @param url
     * @param param
     * @return
     */
    public static JSONObject post2(String url, String param) {
        String post = post(url, param, 1);

        if(StringUtil.notEmpty(post)){
            try {
                JSONObject jsonObject = JSON.parseObject(post);
                if(!jsonObject.containsKey("status")){
                    jsonObject.put("status",true);
                }
                if(!jsonObject.containsKey("message")){
                    jsonObject.put("message","success!");
                }
                return jsonObject;
            }catch (JSONException e){
                log.error(e.getMessage());
                return JSON.parseObject("{\"message\":\"post request error\",\"status\":false}");
            }
        }

        return JSON.parseObject("{\"message\":\"post request error\",\"status\":false}");
    }

    public static String get(String url ,int num){
        log.info("发送get请求地址,{}", url);

        String response = "";// 要返回的response信息
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(socketTimeout);
        GetMethod getMethod = new GetMethod(url);
        getMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //重试3次
        for (int i = 0; i < num; i++) {
            try {
                if (HttpStatus.SC_OK == httpClient.executeMethod(getMethod))
                    break;
            } catch (IOException e) {
                log.error("发送get请求异常,{},{}", getMethod.getStatusLine(), e);
            }
        }

        try {
            response = getMethod.getResponseBodyAsString();
            log.info("发送get请求返回结果,{}", response);
        } catch (IOException e) {
            log.error("发送get请求异常,{}", e);
        }

        getMethod.releaseConnection();
        return response;
    }

    /**
     * 发送get请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        return get(url,3);
    }

    /**
     * 发送get请求,新封装的方法
     *
     * @param url
     * @return
     */
    public static JSONObject get2(String url) {
        String get = get(url, 1);

        if(StringUtil.isEmpty(get)){
            return JSON.parseObject("{\"message\":\"请求失败\",\"status\":false}");
        }

        return JSON.parseObject(get);
    }

    /**
     * 发送form-data类型的数据
     * @param url
     * @param param
     * @return
     */
    public static String postWithParamsForString(String url, NameValuePair[] param){
        log.info("发送form-data类型post请求地址,{}",url);

        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(socketTimeout);
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //postMethod.setRequestEntity();
        if (!StringUtils.isEmpty(param)) {
            postMethod.setRequestBody(param);
        }
        String response = "";// 要返回的response信息
        //重试3次
        for (int i = 0; i < 2; i++) {
            try {
                if (HttpStatus.SC_OK == httpClient.executeMethod(postMethod))
                    break;
            } catch (IOException e) {
                log.error("发送post请求异常,{},{}", postMethod.getStatusLine(), e);
            }
        }

        try {
            response = postMethod.getResponseBodyAsString();
            log.info("发送post请求返回结果,{}", response);
        } catch (IOException e) {
            log.error("发送http请求的返回信息异常,{}", e);
        }

        postMethod.releaseConnection();

        return response;
    }
}

